package com.yangrd.airship.generator.page.impl;

import com.alibaba.fastjson.JSON;
import com.yangrd.airship.generator.page.enhance.TranslateHelper;
import org.springframework.web.client.RestTemplate;

/**
 * description: BingTranslateService
 *
 * @author yangrd
 * @date 2020/9/15
 */
public class YouDaoTranslateHelper implements TranslateHelper {

    private final RestTemplate client = new RestTemplate();

    @Override
    public String translateCn(String english) {
        return JSON.parseObject(get(english)).getJSONArray("translateResult").getJSONArray(0).getJSONObject(0).getString("tgt");
    }


    /**
     * @param body
     * @return [
     * {
     * "detectedLanguage": {
     * "language": "en",
     * "score": 1.0
     * },
     * "translations": [
     * {
     * "text": "你好",
     * "transliteration": {
     * "text": "nǐ hǎo",
     * "script": "Latn"
     * },
     * "to": "zh-Hans",
     * "sentLen": {
     * "srcSentLen": [
     * 5
     * ],
     * "transSentLen": [
     * 2
     * ]
     * }
     * }
     * ]
     * }
     * ]
     */
    private String get(String key) {
        String url = "http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=" + key;
        //  输出结果
        return client.getForObject(url, String.class);
    }
}
